﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Windows.Browser;
using PRI_SliverlightSS;

namespace PRI_SliverlightSS_App
{
    public partial class PRI_SliverlightSS : UserControl
    {
        PRI_Albums m_oPRI_Albums = null;

        string m_strProxyURL = "";
        string m_InitProperty_PicasaUserName = string.Empty;
        AlbumType m_InitProperty_AlbumType = AlbumType.AT_Picasa;

        void SetHTMLProperties(StartupEventArgs e)
        {
            try
            {
                //string sParameters = System.Windows.Browser.HtmlPage.Plugin.GetProperty("initParams").ToString(); //to get directly

                switch (e.InitParams["album_type"].Trim())
                {
                    case "picasa":
                        {
                            m_InitProperty_AlbumType = AlbumType.AT_Picasa;
                            m_InitProperty_PicasaUserName = e.InitParams["picasa_userid"].Trim();
                            break;
                        }
                    case "flickr":
                        {
                            m_InitProperty_AlbumType = AlbumType.AT_Flickr;
                            break;
                        }
                    default:
                        {
                            break;
                        }
                }

            }
            catch (Exception)
            {
                m_InitProperty_AlbumType = AlbumType.AT_Picasa;
                m_InitProperty_PicasaUserName = "clickalbum";
            }

            try
            {
                m_strProxyURL = e.InitParams["proxy_url"].Trim();
            }
            catch (Exception)
            {
                m_strProxyURL = string.Empty;  //Set default
            }
        }

        public PRI_SliverlightSS(StartupEventArgs e)
        {
            InitializeComponent();
            SetHTMLProperties(e);

            //Subscribe Global events
            Application.Current.Host.Content.FullScreenChanged += new EventHandler(Content_FullScreenChanged);
        }


        private void ssUserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //SetupHeight
            canvasSlides.Visibility = Visibility.Collapsed;

            LayoutRoot.Width = Application.Current.Host.Content.ActualWidth;
            LayoutRoot.Height = Application.Current.Host.Content.ActualHeight;
            canvasAlbums.Width = LayoutRoot.Width;
            canvasAlbums.Height = LayoutRoot.Height;
            Set_FullScreenTopNav_Image();

            if (canvasAlbums.Height < canvasAlbums.Width)
            {
                canvasAlbumsPics.Width = canvasAlbums.Height;
                canvasAlbumsPics.Height = canvasAlbums.Height;
            }
            else
            {
                canvasAlbumsPics.Width = canvasAlbums.Width;
                canvasAlbumsPics.Height = canvasAlbums.Width;
            }

            sb_spNavTop.Begin();

            IntiSSSControl(m_InitProperty_AlbumType, m_InitProperty_PicasaUserName);

            //jeremyfrimer  ossilap khurtwilliams   901Photography
            //IntiSSSControl(AlbumType.AT_Picasa, "NaKeuD");
        }

        void IntiSSSControl(AlbumType _album_type,  string _user_name)
        {
            bool bPlay1StAlbum = false;
            spBrowse.Visibility = Visibility.Collapsed;
            spNav.Visibility = Visibility.Collapsed;

            #region ****** Get PRI_Albums Object ******

            switch (_album_type)
            {
                case AlbumType.AT_Picasa:
                    {
                        m_oPRI_Albums = new PRI_PicasaFeedReader();
                        m_oPRI_Albums.ProxyURL = m_strProxyURL;
                        m_oPRI_Albums.Event_AlbumsReady += new Action(this.m_oPRI_Albums_Event_AlbumsReady);
                        m_oPRI_Albums.Event_SlidesReady += new Action(this.m_oPRI_Albums_Event_SlidesReady);
                        //((PRI_PicasaFeedReader)m_oPRI_Albums).GetAlbums("clickalbum");
                        //PRI_PicasaFeedReader)m_oPRI_Albums).GetAlbums("NaKeuD");
                        ((PRI_PicasaFeedReader)m_oPRI_Albums).GetAlbums(_user_name);
                        break;
                    }
                case AlbumType.AT_Flickr:
                    {
                        throw new Exception("Not implemented (AT_Picasa)");
                    }
                default:    //AlbumType.AT_Local
                    {
                        throw new Exception("Not implemented (AT_Local)");
                    }
            }

            #endregion

            if (bPlay1StAlbum)
            {
                #region ****** SlideShow ******

                switch (m_oPRI_Albums._AlbumType)
                {
                    case AlbumType.AT_Picasa:
                        {
                            PRI_PicasaFeedReader oPRI_PicasaFeedReader = m_oPRI_Albums as PRI_PicasaFeedReader;
                            oPRI_PicasaFeedReader.GetAlbumSlides(oPRI_PicasaFeedReader.PicasaUsername, m_oPRI_Albums._Albums[0].ID);//"5217444839515557505");
                            break;
                        }
                    case AlbumType.AT_Flickr:
                        {
                            break;
                        }
                    case AlbumType.AT_Local:
                        {
                            break;
                        }
                }
                #endregion
                SetupSlideShow();
            }
        }

        #region ****** Albums ******

        void m_oPRI_Albums_Event_AlbumsReady()
        {
            DrawAlbumCircle();
        }

        public void DrawAlbumCircle()
        {
            if(m_oPRI_Albums._Albums.Count <= 0)
            {
                tbBrowseInvalidUser.Text = "Invalid Username";
                tbBrowseInvalidUser.Visibility = Visibility.Visible;
                spLoading.Visibility = Visibility.Collapsed;

                ShowBrowse();
                return;
            }

            //canvasAlbums.Children.Clear();
            canvasAlbumsPics.Children.Clear();
            
            if (SSError.eErrorCodes.NoError != m_oPRI_Albums._LastError.ErrorCode)
            {
                //Display Error Image
                return;
            }

            double dAlbumPicHeight = 80.0;
            double dAlbumPicWidth = 102.0;
            double dMaxSideLength = 0.0;
            double dShiftCenter = 0.0;

            if (dAlbumPicHeight > dAlbumPicWidth)
            {
                dMaxSideLength = dAlbumPicHeight / 2;
            }
            else
            {
                dMaxSideLength = dAlbumPicWidth / 2;
            }

            dShiftCenter = dMaxSideLength / 2;


            Point oPointCenterScreen = new Point(canvasAlbumsPics.Width / 2 , canvasAlbumsPics.Height / 2);
            Point oStartPoint = new Point((canvasAlbumsPics.Width / 2), dMaxSideLength);

            TranslateTransform oTranslateTransform = null;
            RotateTransform oRotateTransform = new RotateTransform();
            oRotateTransform.CenterX = oPointCenterScreen.X;
            oRotateTransform.CenterY = oPointCenterScreen.Y;

            int iAlbums = m_oPRI_Albums._Albums.Count;
            bool bSelectAlbumFlag = false;

            for (int i = 0; i < iAlbums; i++)
            {
                #region Create Image
                /*
                //string strImageXAMLC = string.Format(strImageXAML, i);

                Image oImageAlbumCircle = new Image();
                oImageAlbumCircle.Height = dAlbumPicHeight;
                oImageAlbumCircle.Width = dAlbumPicWidth;
                oImageAlbumCircle.VerticalAlignment = VerticalAlignment.Top;
                oImageAlbumCircle.HorizontalAlignment = HorizontalAlignment.Left;
                oImageAlbumCircle.Stretch = Stretch.UniformToFill;
                oImageAlbumCircle.Opacity = 0.5;
                oImageAlbumCircle.MouseEnter += new MouseEventHandler(oImageAlbumCircle_MouseEnter);
                oImageAlbumCircle.MouseLeave += new MouseEventHandler(oImageAlbumCircle_MouseLeave);
                oImageAlbumCircle.MouseLeftButtonUp += new MouseButtonEventHandler(oImageAlbumCircle_MouseLeftButtonUp);
                oImageAlbumCircle.Tag = m_oPRI_Albums._Albums[i];

                EllipseGeometry oEllipseGeometry = new EllipseGeometry();
                oEllipseGeometry.RadiusX = dAlbumPicWidth / 2;
                oEllipseGeometry.RadiusY = dAlbumPicHeight / 2;
                oEllipseGeometry.Center = new Point(dAlbumPicWidth / 2, dAlbumPicHeight / 2);
                oImageAlbumCircle.Clip = oEllipseGeometry;

                //oImage.Source = new BitmapImage(new Uri(string.Format("http://localhost/priyakant_com_silverlight/gallery/kids/lg/{0}.jpg", i+1)));
                oImageAlbumCircle.Source = new BitmapImage(new Uri(m_oPRI_Albums._Albums[i].ThumbnailURL));
                canvasAlbums.Children.Add(oImageAlbumCircle);
                 * */
                #endregion

                Border oBorderAlbumCircle = null;

                #region Create Border
                String xamlAlbumCoverImage = "<Border x:Name=\"borderAlbumCoverImage{0}\" xmlns=\"http://schemas.microsoft.com/client/2007\"  xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" Height=\"80\" Width=\"104\" Background=\"DarkOrange\" Opacity=\"0.5\" HorizontalAlignment=\"Center\" VerticalAlignment=\"Center\">" +
                            "<Border.Clip>" +
                            "<EllipseGeometry RadiusX=\"52\" RadiusY=\"40\" Center=\"52,40\" >" +
                            "</EllipseGeometry>" +
                            "</Border.Clip>" +
                            "<Image Source=\"{1}\" Width=\"100\" Height=\"76\" Stretch=\"UniformToFill\" HorizontalAlignment=\"Center\" VerticalAlignment=\"Center\">" +
                            "<Image.Clip>" +
                            "<EllipseGeometry RadiusX=\"50\" RadiusY=\"38\" Center=\"50,38\" >" +
                            "</EllipseGeometry>" +
                            "</Image.Clip>" +
                            "</Image>" +
                            "</Border>";

                String xamlString = string.Format(xamlAlbumCoverImage, i, m_oPRI_Albums._Albums[i].ThumbnailURL);
                oBorderAlbumCircle = (Border)System.Windows.Markup.XamlReader.Load(xamlString);

                oBorderAlbumCircle.MouseEnter += new MouseEventHandler(oBorderAlbumCircle_MouseEnter);
                oBorderAlbumCircle.MouseLeave += new MouseEventHandler(oBorderAlbumCircle_MouseLeave);
                oBorderAlbumCircle.MouseLeftButtonUp += new MouseButtonEventHandler(oBorderAlbumCircle_MouseLeftButtonUp);

                #endregion

                oBorderAlbumCircle.Tag = m_oPRI_Albums._Albums[i];

                oRotateTransform.Angle = (360.0 / iAlbums) * i;
                Point oPointT = oRotateTransform.Transform(oStartPoint);
                oPointT.X -= (dAlbumPicWidth / 2);
                oPointT.Y -= (dAlbumPicHeight / 2);

                oTranslateTransform = new TranslateTransform();
                oTranslateTransform.X = oPointT.X;
                oTranslateTransform.Y = oPointT.Y;
                oBorderAlbumCircle.RenderTransform = oTranslateTransform;
                //canvasAlbums.Children.Add(oBorderAlbumCircle);
                canvasAlbumsPics.Children.Add(oBorderAlbumCircle);

                if (!bSelectAlbumFlag)
                {
                    bSelectAlbumFlag = true;
                    SelectAlbum(oBorderAlbumCircle);
                }
            }

            spLoading.Visibility = Visibility.Collapsed;
            canvasAlbums.Visibility = Visibility.Visible;
        }

        void oBorderAlbumCircle_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            spLoading.Visibility = Visibility.Visible;
            slideImage.Source = null; ;
            slideImage.Tag = null;

            Border oBorderAlbumCircle = (Border)sender;
            AlbumInfo oAlbumInfo = oBorderAlbumCircle.Tag as AlbumInfo;

            switch (m_oPRI_Albums._AlbumType)
            {
                case AlbumType.AT_Picasa:
                    {
                        PRI_PicasaFeedReader oPRI_PicasaFeedReader = (PRI_PicasaFeedReader)m_oPRI_Albums;
                        oPRI_PicasaFeedReader.GetAlbumSlides(oPRI_PicasaFeedReader.PicasaUsername, oAlbumInfo.ID);
                        break;
                    }
                case AlbumType.AT_Flickr:
                    {
                        break;
                    }
                case AlbumType.AT_Local:
                    {
                        break;
                    }
            }

            StopTimer();
            SetupSlideShow();
        }

        void oBorderAlbumCircle_MouseLeave(object sender, MouseEventArgs e)
        {
            //Border oBorderAlbumCircle = (Border)sender;
            /*
            if (null != m_sbAlbumCoverImage)
            {
                m_sbAlbumCoverImage.Stop();
            }
             * */
        }

        Storyboard m_sbAlbumCoverImage = null;
        DoubleAnimation m_DoubleAnimationImage = null;
        void oBorderAlbumCircle_MouseEnter(object sender, MouseEventArgs e)
        {
            Border oBorderAlbumCircle = (Border)sender;
            SelectAlbum(oBorderAlbumCircle);
        }

        void SelectAlbum(Border _border_album_circle)
        {
            AlbumInfo oAlbumInfo = (AlbumInfo)_border_album_circle.Tag;

            spAlbumInfoImage.Source = new BitmapImage(new Uri(oAlbumInfo.ThumbnailURL));
            txtAlbumInfo_Name.Text = oAlbumInfo.Title;
            txtAlbumInfo_Author.Text = string.Format("Author: {0}. [{1} of {2}] ", m_oPRI_Albums._AuthorInfo.Name, oAlbumInfo.AlbumCount, m_oPRI_Albums._Albums.Count);
            txtAlbumInfo_PublishedDate.Text = oAlbumInfo.PublishedDate;

            if (null == m_sbAlbumCoverImage)
            {
                DoubleAnimation myDoubleAnimation1 = new DoubleAnimation();
                myDoubleAnimation1.From = 0.4;
                myDoubleAnimation1.To = 1.0;
                myDoubleAnimation1.AutoReverse = true;
                myDoubleAnimation1.RepeatBehavior = RepeatBehavior.Forever;

                Duration duration = new Duration(TimeSpan.FromSeconds(10));
                Storyboard sb = new Storyboard();
                sb.Duration = duration;
                sb.Children.Add(myDoubleAnimation1);

                m_DoubleAnimationImage = myDoubleAnimation1;
                Storyboard.SetTargetProperty(myDoubleAnimation1, new PropertyPath("(Opacity)"));
                //oImage.Resources.Add(sb);
                m_sbAlbumCoverImage = sb;
                //m_sbAlbumCoverImage.AutoReverse = true;
                m_sbAlbumCoverImage.RepeatBehavior = RepeatBehavior.Forever;

                Storyboard.SetTarget(m_DoubleAnimationImage, _border_album_circle);
                m_sbAlbumCoverImage.Begin();
            }

            m_sbAlbumCoverImage.Stop();
            Storyboard.SetTarget(m_DoubleAnimationImage, _border_album_circle);
            m_sbAlbumCoverImage.Begin();

            /*
                <Storyboard x:Name="myStoryboard">
      <DoubleAnimation
        Storyboard.TargetName="MyAnimatedRectangle"
        Storyboard.TargetProperty="Opacity"
        From="1.0" To="0.0" Duration="0:0:5" 
        AutoReverse="True" />
    </Storyboard>  */
        }

        #endregion

        #region ****** Slides Timer ******
        DispatcherTimer m_oDispatcherTimer = null;
        
        void StartTimer(TimeSpan _ts)
        {
            if (null == m_oDispatcherTimer)
            {
                m_oDispatcherTimer = new DispatcherTimer();
                m_oDispatcherTimer.Tick += new EventHandler(m_oDispatcherTimer_Tick);
            }
            m_oDispatcherTimer.Interval = _ts;

            StartTimer();
        }

        void StartTimer()
        {
            if (null == m_oDispatcherTimer) { return; }

            m_oDispatcherTimer.Start();

            if (m_biNavPlayPause_Pause == null)
            {
                m_biNavPlayPause_Pause = new BitmapImage(new Uri("/images/gray/pause.png", UriKind.Relative));
            }
            imgNavPlayPause.Source = m_biNavPlayPause_Pause;
            m_IsAlbumPlaying = true;
        }

        void StopTimer()
        {
            if (null == m_oDispatcherTimer) { return; }

            m_oDispatcherTimer.Stop();

            if (m_biNavPlayPause_Play == null)
            {
                m_biNavPlayPause_Play = new BitmapImage(new Uri("/images/gray/play.png", UriKind.Relative));
            }
            imgNavPlayPause.Source = m_biNavPlayPause_Play;

            m_IsAlbumPlaying = false;
        }

        void ToggelTimer()
        {
            if (null == m_oDispatcherTimer) { return; }

            if (m_oDispatcherTimer.IsEnabled)
            {
                StopTimer();
            }
            else
            {
                StartTimer();
            }
        }

        bool m_IsAlbumPlaying = false;
        void PauseTimer()
        {
            m_oDispatcherTimer.Stop();
        }

        void ResumeTimer()
        {
            if (m_IsAlbumPlaying)
            {
                m_oDispatcherTimer.Start();
            }
        }

        void m_oDispatcherTimer_Tick(object sender, EventArgs e)
        {
            SetNextSlide();
        }
        #endregion

        #region ****** Slides ******

        bool m_SetupSlideShowDone = false;
        int iVisibleThumbCount = 6;

        void m_oPRI_Albums_Event_SlidesReady()
        {
            StartSlideShow();
        }

        void StartSlideShow()
        {
            int iImgCount = 0;

            string strImageThumb =
                //"<Image x:Name=\"imageThumb_{0}\" Source=\"{1}\" Width=\"40\" Height=\"40\" Visibility=\"Collapsed\" Margin=\"0\" Stretch=\"UniformToFill\" VerticalAlignment=\"Bottom\" xmlns=\"http://schemas.microsoft.com/client/2007\"  xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" >" +
                "<Image x:Name=\"imageThumb_{0}\" Width=\"40\" Height=\"40\" Visibility=\"Collapsed\" Margin=\"0\" Stretch=\"UniformToFill\" VerticalAlignment=\"Bottom\" xmlns=\"http://schemas.microsoft.com/client/2007\"  xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" >" +
                (m_ThumbAnimationMathod == ThumbAnimationMathod.ThumbAnimationMathod_ShakeIt ?
                "<Image.RenderTransform><RotateTransform Angle=\"0\" CenterX=\"24\" CenterY=\"24\" /></Image.RenderTransform>" :
                "<Image.RenderTransform><TranslateTransform Y=\"0\" /></Image.RenderTransform>") +
                "</Image>";

            spNavPic.Children.Clear();
            foreach (PRI_Slide _slide in m_oPRI_Albums._CurrentSlides._slides)
            {
                _slide._page = (int)(_slide._index / iVisibleThumbCount);    //Page

                Image oImageThumb = null;
                String xamlString = string.Format(strImageThumb, iImgCount, _slide._thumb_medium._url);
                oImageThumb = (Image)System.Windows.Markup.XamlReader.Load(xamlString);
                oImageThumb.MouseEnter += new MouseEventHandler(this.ThumbMouseEnter);
                oImageThumb.MouseLeave += new MouseEventHandler(this.ThumbMouseLeave);
                oImageThumb.SizeChanged += new SizeChangedEventHandler(this.TN_SizeChanged);
                oImageThumb.MouseLeftButtonUp += new MouseButtonEventHandler(oImageThumb_MouseLeftButtonUp);
                oImageThumb.Tag = _slide;
                _slide._FrameworkElement = oImageThumb;

                iImgCount++;

                spNavPic.Children.Add(oImageThumb);
            }

            StartTimer(TimeSpan.FromSeconds(6));

            spNav.Visibility = Visibility.Visible;
            spNavPic.Visibility = Visibility.Visible;

            SetSlide(0);

            canvasAlbums.Visibility = Visibility.Collapsed;
            canvasSlides.Visibility = Visibility.Visible;

            spLoading.Visibility = Visibility.Collapsed;
        }

        void SetupSlideShow()
        {
            if (m_SetupSlideShowDone)
            {
                return;
            }

            m_SetupSlideShowDone = true;

            spThumbImage.Visibility = Visibility.Collapsed;
            spNavPic.Visibility = Visibility.Collapsed;

            slideImage.Width = LayoutRoot.Width - slideImageBorder.BorderThickness.Left - slideImageBorder.BorderThickness.Right;
            slideImage.Height = LayoutRoot.Height - slideImageBorder.BorderThickness.Top - slideImageBorder.BorderThickness.Bottom;

            slideImage.BindingValidationError += new EventHandler<ValidationErrorEventArgs>(slideImage_BindingValidationError);
            slideImage.ImageFailed += new EventHandler<ExceptionRoutedEventArgs>(slideImage_ImageFailed);
            slideImage.Loaded += new RoutedEventHandler(slideImage_Loaded);

            slideImage.Tag = null;

            TranslateNav();
        }

        void slideImage_Loaded(object sender, RoutedEventArgs e)
        {
        }

        void slideImage_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
        }

        void slideImage_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
        }

        void SetNextSlide()
        {
            if (m_oPRI_Albums._CurrentSlides.IsEmpty) { return; }

            m_oPRI_Albums._CurrentSlides.SetNextIndex();

            SetSlide(m_oPRI_Albums._CurrentSlides._CurrentIndex);
        }

        public enum ThumbAnimationMathod
        {
            ThumbAnimationMathod_ShakeIt = 0,
            ThumbAnimationMathod_JumpIt = 1,
        }

        void SetSlide(int _index)
        {
            StopThumbAnimation();

            if (Application.Current.Host.Content.IsFullScreen)
            {
                SetSlide(m_oPRI_Albums._CurrentSlides._slides[_index], m_oPRI_Albums._CurrentSlides._slides[_index]._content_url);
            }
            else
            {
                SetSlide(m_oPRI_Albums._CurrentSlides._slides[_index], m_oPRI_Albums._CurrentSlides._slides[_index]._thumb_large._url);
            }

            //Storyboard.SetTarget(sbUC_ShakeIt_DA, m_oPRI_Albums._CurrentSlides._slides[_index]._FrameworkElement.RenderTransform);
            //sbUC_ShakeIt.Begin();
            StartThumbAnimation(m_oPRI_Albums._CurrentSlides._slides[_index]._FrameworkElement);

            txtSlideCounter.Text = string.Format("{0}/{1}", (_index + 1), m_oPRI_Albums._CurrentSlides._slides.Count);
        }

        void SetSlide(PRI_Slide _slide, string _url)
        {
            //SetSlide(_slide, new BitmapImage(new Uri(_url)));
            Download_MainSlideImage(_slide, _url);
        }

        void SetSlide(PRI_Slide _slide, BitmapImage _bitmap_image)
        {
            UpdateThumbs();

            slideImage.Source = _bitmap_image;
            slideImage.Tag = _slide;
            txtComments.Text = _slide._description;
        }

        ThumbAnimationMathod m_ThumbAnimationMathod = ThumbAnimationMathod.ThumbAnimationMathod_JumpIt;
        //ThumbAnimationMathod m_ThumbAnimationMathod = ThumbAnimationMathod.ThumbAnimationMathod_ShakeIt;

        void StartThumbAnimation(FrameworkElement _fe)
        {
            switch (m_ThumbAnimationMathod)
            {
                case ThumbAnimationMathod.ThumbAnimationMathod_JumpIt:
                    {
                        Storyboard.SetTarget(sbUC_JumpIt_DA, _fe.RenderTransform);
                        sbUC_JumpIt.Begin();
                        break;
                    }
                case ThumbAnimationMathod.ThumbAnimationMathod_ShakeIt:
                    {
                        Storyboard.SetTarget(sbUC_ShakeIt_DA, _fe.RenderTransform);
                        sbUC_ShakeIt.Begin();
                        break;
                    }
            }
        }

        void StopThumbAnimation()
        {
            switch (m_ThumbAnimationMathod)
            {
                case ThumbAnimationMathod.ThumbAnimationMathod_JumpIt:
                    {
                        sbUC_JumpIt.Stop();
                        break;
                    }
                case ThumbAnimationMathod.ThumbAnimationMathod_ShakeIt:
                    {
                        sbUC_ShakeIt.Stop();
                        break;
                    }
            }
        }

        void UpdateThumbs()
        {
            int iCurrentPage = (int)(m_oPRI_Albums._CurrentSlides._CurrentIndex / iVisibleThumbCount);

            foreach (PRI_Slide _slide in m_oPRI_Albums._CurrentSlides._slides)
            {
                if (_slide._page != iCurrentPage)
                {
                    _slide._FrameworkElement.Visibility = Visibility.Collapsed;
                }
                else
                {
                    if (!_slide._thumb_loaded)
                    {
                        Image oImage = _slide._FrameworkElement as Image;
                        oImage.Source = new BitmapImage(new Uri(_slide._thumb_medium._url));
                        _slide._thumb_loaded = true;
                    }

                    _slide._FrameworkElement.Opacity = 1;
                    _slide._FrameworkElement.Visibility = Visibility.Visible;
                }
            }
        }

        void TranslateNav()
        {
            TranslateTransform oTranslateTransform = new TranslateTransform();
            oTranslateTransform.Y = LayoutRoot.Height - spNav.Height - 3;
            oTranslateTransform.X = (LayoutRoot.Width - spNav.Width) / 2;
            spNav.RenderTransform = oTranslateTransform;
        }

        void oImageThumb_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Image oImage = sender as Image;
            PRI_Slide _slide = (PRI_Slide)oImage.Tag;

            if (m_oPRI_Albums._CurrentSlides._CurrentIndex == _slide._index)
            {
                return;
            }

            StopTimer();  //Stop

            m_oPRI_Albums._CurrentSlides._CurrentIndex = _slide._index;
            SetSlide(m_oPRI_Albums._CurrentSlides._CurrentIndex);

            StartTimer();  //Start
        }

        void oImageThumb_MouseLeave(object sender, MouseEventArgs e)
        {
            Image oImage = sender as Image;
            spThumbImage.Visibility = Visibility.Collapsed;
        }

        void oImageThumb_MouseEnter(object sender, MouseEventArgs e)
        {
            try
            {
                Image oImage = sender as Image;
                PRI_Slide _slide = (PRI_Slide)oImage.Tag;

                TranslateTransform oTranslateTransform = new TranslateTransform();
                oTranslateTransform.Y = LayoutRoot.Height - spNav.Height - spThumbImage.Height - 4;
                oTranslateTransform.X = ((LayoutRoot.Width - spNav.Width - (spThumbImage.Width/2)) / 2) + spNavLeft.Width + ((_slide._index % iVisibleThumbCount) * 42);   //7  == "No of thums displaying on screen" + 1 == (6+1)
                spThumbImage.RenderTransform = oTranslateTransform;

                imgThumbImage.Source = new BitmapImage(new Uri(_slide._thumb_medium._url));
                spThumbImage.Visibility = Visibility.Visible;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        void spNav_MouseLeave(object sender, MouseEventArgs e)
        {
            UIElement oNavTopOrBottom = sender as UIElement;
            oNavTopOrBottom.Opacity = 0;
            //spNav.Opacity = 0;
            //spNav.Visibility = Visibility.Collapsed;
        }

        void spNav_MouseEnter(object sender, MouseEventArgs e)
        {
            UIElement oNavTopOrBottom = sender as UIElement;
            oNavTopOrBottom.Opacity = 1;

            //spNav.Opacity = 1;
            //spNav.Visibility = Visibility.Visible;
        }

        double m_dblWidth_Original = -1;
        double m_dblHeight_Original = -1;
        void Content_FullScreenChanged(object sender, EventArgs e)
        {
            if (Application.Current.Host.Content.IsFullScreen)
            {
                if (m_dblWidth_Original < 0)
                {
                    m_dblWidth_Original = LayoutRoot.Width;
                    m_dblHeight_Original = LayoutRoot.Height;
                }

                LayoutRoot.Width = Application.Current.Host.Content.ActualWidth;
                LayoutRoot.Height = Application.Current.Host.Content.ActualHeight;
                slideImage.Width = LayoutRoot.Width - slideImageBorder.BorderThickness.Left - slideImageBorder.BorderThickness.Right;
                slideImage.Height = LayoutRoot.Height - slideImageBorder.BorderThickness.Top - slideImageBorder.BorderThickness.Bottom;
            }
            else
            {
                LayoutRoot.Width = m_dblWidth_Original;
                LayoutRoot.Height = m_dblHeight_Original;
                slideImage.Width = LayoutRoot.Width - slideImageBorder.BorderThickness.Left - slideImageBorder.BorderThickness.Right;
                slideImage.Height = LayoutRoot.Height - slideImageBorder.BorderThickness.Top - slideImageBorder.BorderThickness.Bottom;
            }

            Set_FullScreenTopNav_Image();

            TranslateNav();
        }
        #endregion

        #region Download Main Slide Image

        void Download_MainSlideImage(PRI_Slide _slide, string _image_uri)
        {
            PauseTimer();

            WebClient oWebClient_DownloadImage = new WebClient();
            oWebClient_DownloadImage.OpenReadCompleted += new OpenReadCompletedEventHandler(MainSlideImage_OpenReadCompleted);
            oWebClient_DownloadImage.DownloadProgressChanged += new DownloadProgressChangedEventHandler(MainSlideImage_DownloadProgressChanged);
            oWebClient_DownloadImage.OpenReadAsync(new Uri(_image_uri), _slide); //, _image_uri);
            MainSlideImage_ProgressText.Text = "0%";
            spMainSlideImage_ProgressText.Visibility = Visibility.Visible;
        }

        void MainSlideImage_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            MainSlideImage_ProgressText.Text = e.ProgressPercentage.ToString() + "%";
        }

        void MainSlideImage_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            ResumeTimer();

            if (null == e.Result)
            {
                //Some Error. URL not exists
                MainSlideImage_ProgressText.Text = "Some error";
            }
            else if (e.Cancelled)
            {
                //Cancelled
                MainSlideImage_ProgressText.Text = "Cancelled";
            }
            else
            {
                BitmapImage imgsrc = new BitmapImage();
                imgsrc.SetSource(e.Result as Stream);
                SetSlide(e.UserState as PRI_Slide, imgsrc);
                //imgTemp.Source = imgsrc;
                spMainSlideImage_ProgressText.Visibility = Visibility.Collapsed;
            }
        }
        #endregion

        private void ThumbMouseEnter(object sender, MouseEventArgs e)
        {
            FrameworkElement oControl = sender as FrameworkElement;
            
            sbUC_GrowThumb.Stop();

            if (oControl.RenderTransform == null)
            {
                RotateTransform oRotateTransform = new RotateTransform();
            }
            
            PRI_Slide oSlide = oControl.Tag as PRI_Slide;

            sbUC_GrowThumb_DA_Width.To = oSlide._thumb_medium._width;
            sbUC_GrowThumb_DA_Height.To = oSlide._thumb_medium._height;

            Storyboard.SetTarget(sbUC_GrowThumb_DA_Width, oControl);
            Storyboard.SetTarget(sbUC_GrowThumb_DA_Height, oControl);

            sbUC_GrowThumb.Begin();
            
        }

        private void ThumbMouseLeave(object sender, MouseEventArgs e)
        {
            sbUC_ShrinkThumb.Stop();

            FrameworkElement oControl = sender as FrameworkElement;

            Storyboard.SetTarget(sbUC_ShrinkThumb_DA_Width, oControl);
            Storyboard.SetTarget(sbUC_ShrinkThumb_DA_Height, oControl);
            sbUC_ShrinkThumb.Begin();
        }

        private void TN_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            switch (m_ThumbAnimationMathod)
            {
                case ThumbAnimationMathod.ThumbAnimationMathod_ShakeIt:
                    {
                        FrameworkElement oControl = sender as FrameworkElement;
                        RotateTransform oRotateTransform = (RotateTransform)oControl.RenderTransform;
                        oRotateTransform.CenterX = e.NewSize.Width / 2;
                        oRotateTransform.CenterY = e.NewSize.Height / 2;
                        break;
                    }
            }
        }

        private void spNavMain_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            //spNavBackground.Width = spNavMain.ActualWidth;
            spNavBackground.Height = spNavMain.ActualHeight;
        }

        void HideAll()
        {
            //foreach(UIElement _uielement in LayoutRoot.Children)
            //{
            //    _uielement.Visibility = Visibility.Collapsed;
            //}
            spBrowse.Visibility = Visibility.Collapsed;
            canvasAlbums.Visibility = Visibility.Collapsed;
            canvasSlides.Visibility = Visibility.Collapsed;
            spNav.Visibility = Visibility.Collapsed;
            //spNavTop.Visibility = Visibility.Collapsed;   //We never hide this
        }

        void ShowBrowse()
        {
            HideAll();
            spBrowse.Visibility = Visibility.Visible;
        }

        private void buttonBrowsePicasaAlbum_Click(object sender, RoutedEventArgs e)
        {
            tbBrowseInvalidUser.Visibility = Visibility.Collapsed;
            IntiSSSControl(AlbumType.AT_Picasa, tbPicasaUsername.Text);
        }

        private void buttonBrowsePicasaAlbum_Back_Click(object sender, RoutedEventArgs e)
        {

        }

        private void imgNavBrowse_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            ShowBrowse();
        }

        private void imgSelectAlbum_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            canvasAlbums.Visibility = Visibility.Visible;
            canvasSlides.Visibility = Visibility.Collapsed;
            spNav.Visibility = Visibility.Collapsed;
            StopTimer();
        }

        private void imgFullScreenTop_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Application.Current.Host.Content.IsFullScreen = !Application.Current.Host.Content.IsFullScreen;
        }

        BitmapImage m_biFullScreenTopNav_In = null;
        BitmapImage m_biFullScreenTopNav_Out = null;

        private void Set_FullScreenTopNav_Image()
        {
            if (Application.Current.Host.Content.IsFullScreen)
            {
                //Source="/images/arrow_in.png"
                if (m_biFullScreenTopNav_In == null)
                {
                    m_biFullScreenTopNav_In = new BitmapImage(new Uri("/images/arrow_in.png", UriKind.Relative));
                }
                imgFullScreenTop.Source = m_biFullScreenTopNav_In;
            }
            else
            {
                //Source="/images/arrow_out.png"
                if (m_biFullScreenTopNav_Out == null)
                {
                    m_biFullScreenTopNav_Out = new BitmapImage(new Uri("/images/arrow_out.png", UriKind.Relative));
                }
                imgFullScreenTop.Source = m_biFullScreenTopNav_Out;
            }
        }

        private void imgNavSkipFirst_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //StopTimer();  //Stop

            m_oPRI_Albums._CurrentSlides.SetFirstIndex();
            SetSlide(m_oPRI_Albums._CurrentSlides._CurrentIndex);

            //StartTimer();
        }

        private void imgNavSkipPrevPage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //StopTimer();  //Stop

            int ItoAdd = -iVisibleThumbCount - (m_oPRI_Albums._CurrentSlides._slides[m_oPRI_Albums._CurrentSlides._CurrentIndex]._index % iVisibleThumbCount);
            m_oPRI_Albums._CurrentSlides.Skip_N_Indexes(ItoAdd);

            SetSlide(m_oPRI_Albums._CurrentSlides._CurrentIndex);

            //StartTimer();
        }

        BitmapImage m_biNavPlayPause_Play = null;
        BitmapImage m_biNavPlayPause_Pause = null;

        private void imgNavPlayPause_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            ToggelTimer();
        }

        private void imgNavSkipNextPage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //StopTimer();  //Stop

            int ItoAdd = iVisibleThumbCount - (m_oPRI_Albums._CurrentSlides._slides[m_oPRI_Albums._CurrentSlides._CurrentIndex]._index % iVisibleThumbCount);
            m_oPRI_Albums._CurrentSlides.Skip_N_Indexes(ItoAdd);

            SetSlide(m_oPRI_Albums._CurrentSlides._CurrentIndex);

            //StartTimer();
        }

        private void imgNavSkipLast_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //StopTimer();  //Stop

            m_oPRI_Albums._CurrentSlides.SetLastIndex();
            SetSlide(m_oPRI_Albums._CurrentSlides._CurrentIndex);

            //StartTimer();
        }

        private void NavUIElement_MouseEnter(object sender, MouseEventArgs e)
        {
            FrameworkElement oFrameworkElement = sender as FrameworkElement;

            switch (oFrameworkElement.Name)
            {
                case "imgNavBrowse":
                    {
                        switch (m_oPRI_Albums._AlbumType)
                        {
                            case AlbumType.AT_Picasa:
                                {
                                    txtComments.Text = "Browse your public Picasa albums";
                                    break;
                                }
                            case AlbumType.AT_Flickr:
                                {
                                    txtComments.Text = "Browse your public Flickr albums";
                                    break;
                                }
                            default:
                                {
                                    txtComments.Text = "Browse your albums";
                                    break;
                                }
                        }
                        break;
                    }
                case "imgSelectAlbum":
                    {
                        txtComments.Text = "Select another album";
                        break;
                    }
                case "imgFullScreenTop":
                    {
                        txtComments.Text = Application.Current.Host.Content.IsFullScreen ? "Exit full-screen" : "Full-screen (High resolution pictures)";
                        break;
                    }
                default:
                    {
                        txtComments.Text = "";
                        break;
                    }
            }
        }

        private void NavUIElement_MouseLeave(object sender, MouseEventArgs e)
        {
            txtComments.Text = "";
        }
    }
}
